package com.example.demo.connect;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.http.HttpUtil;

/**
 * @title:	HttpURLConnect
 * @author:	许子文
 * @date:	2019年7月15日 
 * @descirption: 调用http的工具类
 */
public class HttpURLConnect {
	/**
	 * @return
	 * @创建时间: 2019年7月15日
	 * @创建人: 许子文
	 * @功能描述: post方式调用http接口
	 * @param ContentType 传入form表示服务端以表单格式接收参数  传入input表示服务端以流的格式接收参数	传入json表示服务端以json的格式接收参数
	 */
	public static String callPostHttp(String url,String data,String ContentType) throws Exception {
		StringBuilder result = new StringBuilder();
		
		HttpURLConnection conn = getHttpURLConnection(url);

		conn.setDoOutput(true);
			
		conn.setDoInput(true);
		
		conn.setRequestMethod("POST");
		
		conn.setUseCaches(false);
		
		conn.setInstanceFollowRedirects(true);
		
		switch (ContentType) {
			case "form"://如果服务端想通过form(request.getParameter())方式获取参数使用这个
				conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
				break;
			case "json"://如果服务端想以json格式处理参数使用这个,这种也是把数据放进流里
				conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
				break;
			case "input"://如果服务端想通过request.getInputeStream方式获参数使用这个
				conn.setRequestProperty("Content-Type", "text/html");
				break;
			default://如果服务端想通过request.getInputeStream方式获参数使用这个
				conn.setRequestProperty("Content-Type", "text/html");
				break;
		}
		
		conn.connect();
		
		//执行conn.getOutputStream()时会自动进行conn.connect()
		if(data!=null) {
			PrintWriter out = new PrintWriter(conn.getOutputStream());
			
			out.write(data);
			
			out.flush();
			
			out.close();
		}
		
		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		
		
		String str = br.readLine();
		
		while(null!=str) {
			result.append(str);
			result.append("\n");
			str = br.readLine();
		}
		
		br.close();
		
		conn.disconnect();
		
		return result.toString();
	}
	
	public static String callGetHttp(String url) throws Exception{
		StringBuilder result = new StringBuilder();
		
		HttpURLConnection conn = getHttpURLConnection(url);
		
		conn.setDoOutput(true);
		
		conn.setDoInput(true);
		
		conn.setRequestMethod("GET");
		
		conn.connect();
		
		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		
		String str = br.readLine();
		
		while(null!=str) {
			result.append(new String(str.getBytes(), "UTF-8"));
			result.append("\n");
			str = br.readLine();
		}
		
		br.close();
		
		conn.disconnect();
		
		return result.toString();
	}
	
	/**
	 * @return
	 * @throws Exception 
	 * @创建时间: 2019年9月5日
	 * @创建人: 许子文
	 * @功能描述: 将request的body中的数据转换为字符串
	 */
	public static String requestBodyToString(HttpServletRequest request) throws Exception {
		InputStream in = null;
		
		BufferedReader br = null;
		
		StringBuilder sb = new StringBuilder();
		in = request.getInputStream();
		
		br = new BufferedReader(new InputStreamReader(in));
		
		String msgline = br.readLine();
		
		while(null!=msgline) {
			sb.append(msgline);
			sb.append("\n");
			msgline = br.readLine();
		}
			
		if(null!=br) {
			br.close();
		}
		if(null!=in) {
			in.close();
		}
		
		return sb.toString();
	}
	
	private static HttpURLConnection getHttpURLConnection(String urlStr) throws Exception  {
		HttpURLConnection conn = null;
		
		
		if(urlStr.startsWith("https")) {
			conn = getHttpsURLConnection(urlStr);
		} else {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection)url.openConnection();
		}
		
		return conn;
	}
	
	private static HttpsURLConnection getHttpsURLConnection(String uriStr) throws Exception {
		KeyManager[] keyManagers = null;
		
		TrustManager[] trustManagers = new TrustManager[] {new DefaultTrustManager()};
		
		SSLContext context = SSLContext.getInstance("TLSv1.2");
		
		context.init(keyManagers, trustManagers, null);
		
		SSLSocketFactory sslFactory = context.getSocketFactory();
		
		URL url = new URL(uriStr);
		
		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
		
		conn.setSSLSocketFactory(sslFactory);
		
		conn.setHostnameVerifier(new HostnameVerifier() {
			
			@Override
			public boolean verify(String arg0, SSLSession arg1) {
				// TODO Auto-generated method stub
				return true;
			}
		});
		
		return conn;
	}
	
	private static final class DefaultTrustManager implements X509TrustManager{

		@Override
		public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}
		
	}
	
	public static void main(String[] args) {
		try {
			/*String resutl = callPostHttp("http://localhost:8007/sys/menu/list","name=配置","form");
			System.out.println(resutl);*/
			
//			String smsUrl = "http://192.168.42.30:30300/api/ims/login/getUserToken";
			String smsUrl = "https://114.55.239.134/auth/login/getrsapubkey";
			Map<String, String> smsDemo = new HashMap<>();
			smsDemo.put("username", "xuziwen");
			
			String sendJson = JSONObject.toJSONString(smsDemo);
			
//			String resp = callPostHttp(smsUrl, sendJson, "json");
//			String resp = callGetHttp(smsUrl);
			String resp = callPostHttp(smsUrl, null, "form");
//			String resp = HttpUtil.get(smsUrl);
			System.out.println(resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
